package com.roadjava.rbac.security;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

public class AESUtil {
    private static final String ALGORITHM = "AES";
    private static final String ALGORITHM_WITH_MODE = "AES/ECB/PKCS5Padding";

    public static String decrypt(String encryptedData, String secretKey) throws Exception {
        if (encryptedData == null || secretKey == null) {
            throw new IllegalArgumentException("解密数据和密钥不能为空");
        }

        byte[] keyBytes = Arrays.copyOf(secretKey.getBytes(StandardCharsets.UTF_8), 16);
        // 确保密钥长度为16位
        SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);

        Cipher cipher = Cipher.getInstance(ALGORITHM_WITH_MODE);
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] decryptedData = cipher.doFinal(encryptedDataBytes);

        return new String(decryptedData, StandardCharsets.UTF_8);
    }
}